package com.sample.rx3.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import com.sample.rx3.AndPerMission
import com.sample.rx3.base.BasicFragment
import com.sample.rx3.databinding.FragmentBlankBinding

class BlankFragment : BasicFragment(), AndPerMission.MultipleCallback,
    AndPerMission.SingleCallback {
    private var mParam1: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            mParam1 = requireArguments().getString(ARG_PARAM1)
        }
    }

    private var _binding: FragmentBlankBinding? = null
    private val binding get() = _binding!!
    private lateinit var singleLauncher: ActivityResultLauncher<String>
    private lateinit var multipleLauncher: ActivityResultLauncher<Array<String>>

    override fun inflaterView(inflater: LayoutInflater, container: ViewGroup?): View? {
        _binding = FragmentBlankBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun afterOnCreate() {
        binding.message.text = mParam1
        binding.message.tag = mParam1
        singleLauncher = AndPerMission.single(this, this)
        multipleLauncher = AndPerMission.multiple(this, this)
        binding.message.setOnClickListener {
            val tag = it.tag as String?
            when {
                TextUtils.equals("memory", tag) -> {
                    singleLauncher.launch(
                        AndPerMission.WRITE_EXTERNAL_STORAGE
                    )
                }
                TextUtils.equals("location", tag) -> {
                    multipleLauncher.launch(
                        arrayOf(
                            AndPerMission.ACCESS_COARSE_LOCATION,
                            AndPerMission.ACCESS_FINE_LOCATION
                        )
                    )
                }
                TextUtils.equals("phone", tag) -> {
                    singleLauncher.launch(AndPerMission.READ_PHONE_STATE)
                }
                else -> {
                    onFrag2Act("camera",null)
                }
            }
        }
    }

    override fun onSingleCallback(successful: Boolean) {
        println(if (successful) "权限获取成功" else "权限获取失败")
    }

    override fun onMultipleCallback(refuseList: MutableList<String>) {
    }

    companion object {
        private const val ARG_PARAM1 = "param1"
        fun newInstance(param1: String?): BlankFragment {
            val fragment = BlankFragment()
            val args = Bundle()
            args.putString(ARG_PARAM1, param1)
            fragment.arguments = args
            return fragment
        }
    }

    override fun unbind() {
        _binding = null
    }
}